package net.seriousinc.SeriousMobile;

import java.io.IOException;

import org.jibble.pircbot.IrcException;
import org.jibble.pircbot.NickAlreadyInUseException;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.viewpagerindicator.TabPageIndicator;
import com.viewpagerindicator.TitleProvider;

public class SeriousMobileActivity extends FragmentActivity {
	
	
	private String[] titles = {"TV", "Chat"};
	private static final int NUM_ITEMS = 2;
	
	WebFragment tv;
	ZenoChatActivity chat;
	
	TabPageIndicator indicator;
	
	PowerManager.WakeLock wl;
	ViewPager pager;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
    	
        super.onCreate(savedInstanceState);
        
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "SeriousMobile");
        wl.acquire();
        setContentView(R.layout.main);
        
        ViewPagerAdapter adapter = new ViewPagerAdapter(this, getSupportFragmentManager());
        pager = (ViewPager)findViewById(R.id.pager);
        indicator = (TabPageIndicator)findViewById(R.id.indicator);
        pager.setAdapter(adapter);
        indicator.setViewPager(pager);
        pager.setCurrentItem(1);
        Configuration newConfig = getResources().getConfiguration();
    	if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
    		indicator.setVisibility(View.GONE);
    	else
    		indicator.setVisibility(View.VISIBLE);
    	
    	class DetailOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {
            @Override
            public void onPageSelected(int position) {
                if(position==0)
                {
                	InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                	imm.hideSoftInputFromWindow(chat.input.getWindowToken(), 0);
                }
            }
        }
    	
    	indicator.setOnPageChangeListener(new DetailOnPageChangeListener());
    }
    
    public boolean onCreateOptionsMenu(Menu menu)
    {
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item)
    {
    	switch(item.getItemId())
    	{
    	case R.id.userlist:
    		pager.setCurrentItem(1);
    		chat.printUserList();
    		return true;
    	case R.id.reconnect:
    		try {
				chat.irc.reconnect();
			} catch (NickAlreadyInUseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IrcException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		tv.getWebView().loadUrl("http://tv.seriousinc.net/mobile.php");
    		return true;
    	case R.id.quit:
    		finish();
    		return true;
    	default:
    		return super.onOptionsItemSelected(item);	
    	}
    }
    
    @Override
    public void onDestroy()
    {
    	super.onDestroy();
    	tv.getWebView().loadData("", "text/html", "UTF-8");
    	wl.release();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	outState.putString("SeriousMobile", "");
        //super.onSaveInstanceState(outState);
    }

    @Override
	public void onBackPressed() {
    	if(chat.isConnected())
    	{
		   Log.d("CDA", "onBackPressed Called");
		   Intent setIntent = new Intent(Intent.ACTION_MAIN);
		   setIntent.addCategory(Intent.CATEGORY_HOME);
		   setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		   startActivity(setIntent);
    	}
    	else
    		super.onBackPressed();
	}
    
    public void submitMessage(View v)
    {
    	chat.submitMessage(v);
    }
    
    public class ViewPagerAdapter extends FragmentPagerAdapter implements TitleProvider
    {
    	Context context;
    	public ViewPagerAdapter(Context context, FragmentManager fm) {
    		super(fm);
    		this.context = context;
    		// TODO Auto-generated constructor stub
    	}    	
    	
    	@Override
    	public String getTitle(int position) {
    		// TODO Auto-generated method stub
    		return titles[position];
    	}
    	
    	@Override
    	public int getCount() {
    		// TODO Auto-generated method stub
    		return NUM_ITEMS;
    	}

		@Override
		public Fragment getItem(int arg0) {
			// TODO Auto-generated method stub
			switch(arg0)
			{
			case 0:
				tv = new WebFragment();
				return tv;
			case 1:
				chat = new ZenoChatActivity();
				Bundle extras = getIntent().getExtras();
				chat.setArguments(extras);
				return chat;
				
			}
			return null;
		}
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
    	super.onConfigurationChanged(newConfig);
    	//setContentView(R.layout.main);
    	if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
    		indicator.setVisibility(View.GONE);
    	else
    		indicator.setVisibility(View.VISIBLE);
    }
}

